package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public int delete(Long id) {
        return permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int save(Permission permission) {
        return permissionMapper.insert(permission);
    }

    @Override
    public Permission get(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> listAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public int update(Permission permission) {
        return permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public PageInfo<Permission> query(QueryObject qo) {
        //int count = permissionMapper.selectForCount(qo);
        //if(count == 0) {
        //    return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), Collections.emptyList(), count);
        //}
        //// 获取总页数
        //int totalPage =  count % qo.getPageSize() == 0?
        //        count / qo.getPageSize() : count / qo.getPageSize() + 1;
        //// 判断当前页是否大于总页数, 如果是, 把总页数作为当前页来查询
        //qo.setCurrentPage(totalPage <= qo.getCurrentPage() ? totalPage : qo.getCurrentPage());
        //List<Permission> permissions = permissionMapper.selectForList(qo);
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Permission> permissions = permissionMapper.selectForList(qo);
        return new PageInfo<>(permissions);
    }

    @Autowired
    private ApplicationContext ctx; // Spring的上下文对象

    @Override
    public void reload() {
        // 解决权限重复添加的问题, 查询所有权限对象的表达式封装成String类型的list集合
        List<String> expressions = permissionMapper.selectAllExpression();

        System.out.println(expressions);
        // 需求: 把每个控制器贴了权限注解的方法转化为权限数据, 并插入到数据库
        // 1. 获取所有的控制器
        Map<String, Object> map = ctx.getBeansWithAnnotation(Controller.class);
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
        }
        // 拿到所有的controller对象
        Collection<Object> controllers = map.values();
        // 2. 遍历获取每个控制器中的方法
        for (Object controller : controllers) {
            // 控制器的字节码对象
            Class<?> clazz = controller.getClass().getSuperclass();
            // 3. 遍历获取到每个方法
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                System.out.println(method);
                //...
                //判断实例是否是Cglib的代理对象
                if (!AopUtils.isCglibProxy(controller)) {
                    continue;//执行下一次循环
                }
                // 4. 判断该方法中是否有贴自定义的注解（shiro提供）
                RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);
                if (annotation != null) {
                    // 5. 从注解中获取权限相关的数据, 并封装为权限对象
                    String name = annotation.value()[1];            // 名字
                    // 方式一: 通过获取注解中手动添加的权限表达式
                    //String expression = annotation.expression(); // 表达式
                    //...
                    // 方式二: 通过反射拼接出来
                    // getName -- 权限定名
                    // getSimpleName -- 普通的类名
                    //String simpleName = clazz.getSimpleName();
                    //simpleName = simpleName.replace("Controller", "");
                    //String expression = StringUtils.uncapitalize(simpleName) + ":" + method.getName(); // employee:delete
                    // 6. 保存到数据库

                    String expression = annotation.value()[0];
                    if (!expressions.contains(expression)) {
                        Permission permission = new Permission();
                        permission.setName(name);
                        permission.setExpression(expression);
                        permissionMapper.insert(permission);
                    }
                }
            }
        }
    }

    @Override
    public List<String> selectByExpressionByEmpId(Long id) {
        return permissionMapper.selectByExpressionByEmpId(id);
    }
}
